import React, { useState } from "react";
import { Position } from "./interface";

interface BoxProps {
  children: React.ReactNode;
  color: string;
  position: Position;
  onMove: (x: number, y: number) => void;
}

interface LastCoordinates {
  x: number;
  y: number;
}

function Box(props: BoxProps) {
  const { children, color, position, onMove } = props;
  const [lastCoordinates, setLastCoordinates] = useState<LastCoordinates | null>(null);
  const divElement = React.useRef<HTMLDivElement>(null);

  function handlePointerDown(e: React.PointerEvent<HTMLDivElement>) {
    // console.dir(e);
    divElement.current!.setPointerCapture(e.pointerId);
    setLastCoordinates({
      x: e.clientX,
      y: e.clientY
    });
  }

  function handlePointerMove(e: React.PointerEvent<HTMLDivElement>) {
    if (lastCoordinates) {
      setLastCoordinates({
        x: e.clientX,
        y: e.clientY
      });

      const dx = e.clientX - lastCoordinates.x;
      const dy = e.clientY - lastCoordinates.y;
      onMove(dx, dy);
    }
  }

  function handlePointerUp() {
    setLastCoordinates(null);
  }

  return (
    <div
      ref={divElement}
      onPointerDown={handlePointerDown}
      onPointerMove={handlePointerMove}
      onPointerUp={handlePointerUp}
      style={{
        width: 100,
        height: 100,
        cursor: "grab",
        backgroundColor: color,
        position: "absolute",
        border: "1px solid black",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        transform: `translate(${position.x}px,${position.y}px)`
      }}
    >
      {children}
    </div>
  );
}

export default Box;
